<script setup>
import { ref, watch, reactive, unref } from 'vue'
import { useVModels, toReactive } from '@vueuse/core'
import { streamFetch } from "../../common/utils/streamFetch"
import defaultSetting from "../../common/utils/defaultSetting"
import utils from "../../common/utils/utils"
import { message, Form } from 'ant-design-vue'

const useForm = Form.useForm;
const emit = defineEmits([
    'update:role_name',
    'update:visible',
    'start',
    'stream',
    'end'
])

let BASE_URL = defaultSetting.requestDomain;
if (process.env.NODE_ENV === "development") {
    BASE_URL = BASE_URL + "/api";
}

const props = defineProps({
    role_name: {
        type: String,
        default: ''
    },
    visible: {
        type: Boolean,
        default: false
    }
})

const { role_name, visible: showVisible } = useVModels(props, emit)

const modelRef = toReactive({
    role_name,
    role_needs: ref('')
})

const rulesRef = reactive({
    role_name: [
        {
            required: true,
            message: '请输入角色名称',
        },
    ]
});

const { validate, validateInfos } = useForm(modelRef, rulesRef);

const labelCol = { span: 24 }
const wrapperCol = { span: 24 }
const confirmLoading = ref(false)

const generate = async (generate_type = 'prompt', options = {}, cb) => {
    let params = {
        generate_type,
        org_id: utils.getOrgId(),
        user_token: utils.getToken(),
        role_name: unref(modelRef.role_name),
        cur_env: utils.isMobile()
            ? "h5"
            : import.meta.env.ELECTRON
                ? "desktop"
                : "pc",
    }

    params = Object.assign(params, options)

    const { responseText } = await streamFetch({
        url: `${BASE_URL}/work_ai/chat/prompt/generated`,
        data: params,
        onMessage: (text) => {
            if (utils.isJSONStr(text)) {
                let res = JSON.parse(text);

                if (utils.isObject(res) && res.msg) {
                    message.error(res.msg);
                    return;
                }
            }

            cb && cb(text)
        },
    }).catch((err) => {
        console.log(err);

        return {
            responseText: '',
        };
    })

    return responseText
}

const confirm = () => {
    validate()
        .then(async () => {
            confirmLoading.value = true
            emit('start', 'prompt')

            let responseText = await generate('prompt', {
                role_needs: unref(modelRef.role_needs),
            }, (text) => {
                emit('stream', {
                    text,
                    type: 'prompt',
                })
            })

            emit('end', {
                text: responseText,
                type: 'prompt',
            })


            const requests = generatedTypes.value.filter(type => type != 'prompt').map((type) => {
                return new Promise((resolve) => {
                    emit('start', type)

                    generate(type, {
                        role_prompt: unref(responseText),
                    }, (text) => {
                        emit('stream', {
                            text,
                            type,
                        })
                    }).then(response => {
                        emit('end', {
                            text: response,
                            type: type,
                        })

                        resolve(response)
                    })
                })
            })

            await Promise.all(requests)

            confirmLoading.value = false
        })
        .catch(err => {
            console.log('error', err)
        })
}

const generatedTypes = ref(['prompt', 'desc', 'welcome'])

watch(showVisible, (val) => {
    if (!val) {
        confirmLoading.value = false
    }
})

const generatedTypeOptions = [
    { label: '角色设定Prompt', value: 'prompt', disabled: true },
    { label: '角色介绍', value: 'desc' },
    { label: '欢迎语设置', value: 'welcome' },
]

defineExpose({
    generate,
})
</script>

<template>
    <a-modal v-model:visible="showVisible" title="请输入你的角色需求" @ok="confirm" :confirmLoading="confirmLoading">
        <a-form :label-col="labelCol" :wrapper-col="wrapperCol" layout="vertical">
            <a-form-item label="角色名称" v-bind="validateInfos.role_name">
                <a-input placeholder="如产品售后咨询、内部培训助手等" v-model:value="modelRef.role_name" :maxlength="12" />
            </a-form-item>
            <a-form-item label="角色需求" v-bind="validateInfos.role_needs">
                <a-textarea
                    placeholder="例如：我需要为新入职的客户经理小刘进行产品知识培训,内容包括公司主要产品的功能、优势、定价等。通过这次培训,我要让小刘对公司产品有全面的了解,以便他更好地执行客户开发与维护工作"
                    v-model:value="modelRef.role_needs" :rows="3" showCount :maxlength="100" />
            </a-form-item>
            <a-form-item label="生成内容选择" v-bind="validateInfos.role_needs">
                <a-checkbox-group v-model:value="generatedTypes" name="checkboxgroup" :options="generatedTypeOptions" />
            </a-form-item>
        </a-form>
    </a-modal>
</template>